/**
 * 邮件发送工具模块
 * 支持SMTP邮件服务
 */

const nodemailer = require('nodemailer');

// 创建邮件传输器
const createTransporter = () => {
  const host = process.env.EMAIL_HOST;
  const port = parseInt(process.env.EMAIL_PORT) || 587;
  const user = process.env.EMAIL_USER;
  const pass = process.env.EMAIL_PASS;

  if (!host || !user || !pass) {
    throw new Error('邮件服务配置缺失，请检查.env文件中的EMAIL_HOST、EMAIL_USER、EMAIL_PASS');
  }

  return nodemailer.createTransport({
    host,
    port,
    secure: port === 465, // true for 465, false for other ports
    auth: {
      user,
      pass
    }
  });
};

/**
 * 发送邮箱验证码
 * @param {string} email - 邮箱地址
 * @param {string} code - 验证码
 * @returns {Promise<{success: boolean, message?: string}>} 发送结果
 */
async function sendEmailVerificationCode(email, code) {
  // 如果未启用邮件服务，返回成功（开发模式）
  if (process.env.EMAIL_ENABLED !== 'true') {
    console.log(`📧 [开发模式] 邮箱验证码: ${code} → ${email}`);
    return { success: true, message: '开发模式：验证码已在日志中显示' };
  }

  try {
    const transporter = createTransporter();

    const mailOptions = {
      from: process.env.EMAIL_FROM || process.env.EMAIL_USER,
      to: email,
      subject: '【快递代拿系统】邮箱验证码',
      html: `
                <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                    <h2 style="color: #333; border-bottom: 2px solid #3b82f6; padding-bottom: 10px;">邮箱验证码</h2>
                    <p style="color: #666; line-height: 1.6;">您好，</p>
                    <p style="color: #666; line-height: 1.6;">您正在验证邮箱，验证码是：</p>
                    <div style="background: #f5f5f5; padding: 30px; text-align: center; margin: 30px 0; border-radius: 8px;">
                        <h1 style="color: #3b82f6; margin: 0; font-size: 36px; letter-spacing: 5px;">${code}</h1>
                    </div>
                    <p style="color: #666; line-height: 1.6;">验证码有效期为 <strong style="color: #ef4444;">10分钟</strong>，请勿泄露给他人。</p>
                    <p style="color: #666; line-height: 1.6;">如果这不是您的操作，请忽略此邮件。</p>
                    <hr style="border: none; border-top: 1px solid #eee; margin: 30px 0;">
                    <p style="color: #999; font-size: 12px; margin: 0;">此邮件由系统自动发送，请勿回复。</p>
                    <p style="color: #999; font-size: 12px; margin: 5px 0 0 0;">© ${new Date().getFullYear()} 快递代拿系统</p>
                </div>
            `
    };

    const info = await transporter.sendMail(mailOptions);
    console.log('📧 邮件发送成功:', info.messageId);
    return { success: true, message: '邮件发送成功' };
  } catch (error) {
    console.error('❌ 邮件发送失败:', error);
    return {
      success: false,
      message: error.message || '邮件发送失败'
    };
  }
}

module.exports = {
  sendEmailVerificationCode
};

